package com.tyc.flink;

/**
 * 从自定义Source中读取数据
 *
 * @author tyc
 * @version 1.0
 * @date 2022-11-16 17:40:48
 */
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Random;

public class StreamSourceTest {

    private volatile static boolean running = true;

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<Integer> dataStreamSource = env.addSource(new MySourceForInt());
        dataStreamSource.print();
        env.execute();
    }

    private static class MySourceForInt implements SourceFunction<Integer> {
        @Override
        public void run(SourceContext<Integer> ctx) throws Exception {
            Random random = new Random();
            while(running) {
                int a = random.nextInt(1000);
                Thread.sleep(200);
                ctx.collect(a);
            }
        }

        @Override
        public void cancel() {
            running = false;
        }
    }
}
